/**
 * TimeLimit
 */

var React = require("react");
var tool = require("../../../utils/tool");
var Validator = require("../../../utils/validator/Validator");

const TimeLimit = React.createClass({
    getDefaultProps: function () {
        return {
            data: {}
        }
    },
    getInitialState: function () {
        return {
            custom: 0,
            start_date: "",
            end_date: "",
            start_time: "",
            end_time: ""
        }
    },
    componentWillMount: function () {
        this.initialize = false;
        this.initialSave = false;
        this.storeData = {};
        this.dateDropperOpts = {
            maxYear: 2050,
            yearsRange: 1,
            animate: false
        };
        this.timeDropperOpts = {
            format: "HH:mm",
            meridians: false,
            setCurrentTime: false
        };
        this.droppers = {
            date: {
                types: ["start_date", "end_date"],
                overlayClassName: "dd-s"
            },
            time: {
                types: ["start_time", "end_time"],
                overlayClassName: "td-overlay"
            }
        };
    },
    componentWillReceiveProps: function (nextProps) {
        var data = nextProps.data;
        if (data && !tool.isEmptyObject(data)) {
            var result = this.checkDefaultData(data);

            data = this.getDefaultData(data);

            var authority = data.set_auth || 0;

            this.storeData = data;
            this.setState({
                custom: data.custom,
                start_date: data.start_date,
                end_date: data.end_date,
                start_time: data.start_time,
                end_time: data.end_time
            });

            if (authority !== 0 && !this.initialSave && !result) {
                this.initialSave = true;
                this.saveData(data);
            }
        }
    },
    componentDidUpdate: function () {
        if (!this.initialize) {
            this.initialize = true;
            this.bindEvent();
        }
        this.initDropper();
    },
    checkDefaultData: function (data) {
        return data.start_date && data.end_date && data.start_time && data.end_time;
    },
    getDefaultData: function (data) {
        var startDefaultDate = this.createFullDate(new Date().getDate()),
            endDefaultDate = this.createFullDate(new Date().getDate() + 1);
        var defaultTime = this.createFullTime();

        var _data = $.extend({}, data);

        _data.custom = _data.custom || 0;
        _data.start_date = _data.start_date || startDefaultDate;
        _data.end_date = _data.end_date || endDefaultDate;
        _data.start_time = _data.start_time || defaultTime;
        _data.end_time = _data.end_time || defaultTime;

        return _data;
    },
    createFullDate: function (setDate) {
        var date = new Date();
        date.setDate(setDate);
        return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    },
    createFullTime: function () {
        var date = new Date();
        return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    },
    bindEvent: function () {
        var me = this;
        var droppers = this.droppers;
        // 关闭日期和时间选择器保存对应数据
        for (var type in droppers) {
            if (droppers.hasOwnProperty(type)) {
                var dropper = droppers[type];
                (function (_type, _dropper) {
                    var types = _dropper.types, className = _dropper.overlayClassName;
                    $(document.body).on("click", "." + className, function () {
                        me.saveDropperData(_type, types);
                    });
                })(type, dropper);
            }
        }
    },
    initDropper: function () {
        $(".dd-w").remove();
        $(".td-wrap").remove();
        $(this.refs.start_date).dateDropper(this.dateDropperOpts);
        $(this.refs.end_date).dateDropper(this.dateDropperOpts);
        $(this.refs.start_time).timeDropper(this.timeDropperOpts);
        $(this.refs.end_time).timeDropper(this.timeDropperOpts);
    },
    handleOnChangeCustom: function (type, isNonauthorized, isNonlimit, e) {
        var element = $(e.target), val = parseInt(element.val());

        // 无权限弹窗
        if (isNonauthorized && isNonlimit) {
            this.nonauthorizedPopup();
            return;
        }

        var param = {};
        param[type] = val;

        this.saveData(param);
    },
    handleOnChangeDate: function (type, e) {
        var element = $(e.target), val = element.val();

        var param = {};
        param[type] = val;

        this.setState(param);
    },
    saveData: function (param) {
        var data = this.props.data;

        var params = $.extend(data, param);
        this.storeData = params;

        this.props.saveRecognizeProperty({
            time_limit: params
        });
    },
    saveDropperData: function (type, types) {
        var param = {};

        var me = this;
        types.forEach(function (_type) {
            param[_type] = $(me.refs[_type]).val();
        });

        if (this.checkValidate(type, types)) {
            this.saveData(param);
        } else {
            this.restoreData(types);
        }
    },
    restoreData: function (types) {
        var me = this;
        types.forEach(function (type) {
            $(me.refs[type]).val(me.storeData[type]);
        });
    },
    checkValidate: function (type, types) {
        // 只对起始日期做合法性校验
        if (type === "date") {
            var startDate = $(this.refs[types[0]]).val(), endDate = $(this.refs[types[1]]).val();

            var validator = Validator();
            validator.addRule(startDate, [{
                validator: "dateRange",
                extra: {value: endDate, spliter: "-"},
                error: "开始日期不能大于结束日期！"
            }]);

            var errors = validator.execute();
            if (errors) {
                alert(errors);
                return false;
            }
        }
        return true;
    },
    handleOnCheckAuthority: function (isNonauthorized, e) {
        if (isNonauthorized) {
            this.nonauthorizedPopup();
        }
    },
    nonauthorizedPopup: function () {
        // var root = this.props.root;
        // this.props.setState({
        //     popupDialog: "nonauthorized"
        // });
        this.props.updateState('popupDialog','nonauthorized');
    },
    render: function () {
        var data = this.props.data;
        // 剩余时间
        var limit = data.auth_time || 0;
        limit = limit > 999 ? "999+" : limit;

        // 权限
        var authority = data.set_auth || 0;

        var isNonlimit = limit === -1;
        var isNonauthorized = authority === 0;

        // 0-->不限制识别时间，1-->自定义可识别时间
        var custom = this.state.custom;

        var content = "";
        // 无权限
        if (isNonauthorized && !isNonlimit) {
            content =
                <div>
                    <div className="text-region">
                        <div className="title">时间限制：</div>
                        <div onClick={ this.nonauthorizedPopup }
                             className={"recognize" + (isNonauthorized ? " disabled" : "")}>
                            <div className="extend">延长识别时间</div>
                        </div>
                        <div className="tip">
                            剩余可识别时间从作品首次发布后开始计算；撤回发布于重新收改发布均不再重新计算剩余时间。
                        </div>
                    </div>
                    <div className="round-region empty">
                        <div className="time">
                            <div className="limit">{ limit }</div>
                            <div className="unit">剩余时间（天）</div>
                        </div>
                        <div className="horn"></div>
                    </div>
                </div>
        } else {
            var roundNode = "", dateTimeNode = "";
            // 不限制识别时间
            if (custom == 0) {
                roundNode =
                    <div className="round-region full">
                        <div className="time">
                            <div className="limit infinite"></div>
                            <div className="unit">不限制时间</div>
                        </div>
                    </div>
                // 自定义可识别时间
            } else {
                dateTimeNode =
                    <div>
                        <div className="date">
                            <span className="date-title">日期</span>
                            <span className="date-item">
                                <input className={isNonauthorized ? "disabled" : ""} ref="start_date" readOnly
                                       onClick={ this.handleOnCheckAuthority.bind(this, isNonauthorized) }
                                       onChange={ this.handleOnChangeDate.bind(this, "start_date") } name="start_date"
                                       type="text" value={ this.state.start_date }/>
                            </span>
                            <span className="spliter">～</span>
                            <span className="date-item">
                                <input className={isNonauthorized ? "disabled" : ""} ref="end_date" readOnly
                                       onClick={ this.handleOnCheckAuthority.bind(this, isNonauthorized) }
                                       onChange={ this.handleOnChangeDate.bind(this, "end_date") } name="end_date"
                                       type="text" value={ this.state.end_date }/>
                            </span>
                        </div>
                        <div className="time">
                            <span className="date-title">每天时段</span>
                            <input className={isNonauthorized ? "disabled" : ""} ref="start_time" readOnly
                                   onClick={ this.handleOnCheckAuthority.bind(this, isNonauthorized) }
                                   onChange={ this.handleOnChangeDate.bind(this, "start_time") } name="start_time"
                                   type="text" value={ this.state.start_time }/>
                            <span className="spliter">～</span>
                            <input className={isNonauthorized ? "disabled" : ""} ref="end_time" readOnly
                                   onClick={ this.handleOnCheckAuthority.bind(this, isNonauthorized) }
                                   onChange={ this.handleOnChangeDate.bind(this, "end_time") } name="end_time"
                                   type="text" value={ this.state.end_time }/>
                        </div>
                    </div>
            }

            content =
                <div>
                    <div className={"text-region" + (custom == 1 ? " dateTime" : "")}>
                        <div className="title">时间限制：</div>
                        <div className="custom">
                            <select className={isNonauthorized ? "disabled" : ""} name="custom"
                                    onChange={ this.handleOnChangeCustom.bind(this, "custom", isNonauthorized, isNonlimit) }
                                    value={ custom }>
                                <option value="0">不限制识别时间</option>
                                <option value="1">自定义可识别时间</option>
                            </select>
                        </div>
                        { dateTimeNode }
                        <div className="tip">
                            在以上时间范围内的作品才能被识别。
                        </div>
                    </div>
                    { roundNode }
                </div>
        }

        return (
            <div className="limit-item">
                { content }
            </div>
        )
    }
});

export default TimeLimit;
